// src/views/login/index.tsx
import { Form, Input, Button, message } from 'antd'
import {
UserOutlined,
LockOutlined
} from '@ant-design/icons';
import { IAdminParams, adminLoginFn } from '../../api/user';
import { useAppDispatch } from '../../store/hooks';
import { changeAdminName, changeCheckedkeys, changeLoginState, changeRole, changeToken } from '../../store/modules/user';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

type IndexProps = {}

// 一定要记得把原来组件库的userName改成 adminname
export const Index = (props: IndexProps) => {

const dispatch = useAppDispatch()

const navigate = useNavigate()

const onFinish = (values: IAdminParams) => {

 // console.log(values)
 adminLoginFn(values).then(res => {
   console.log(res.data)
   switch (res.data.code) {
     case '10005':
       message.error('不存在该账户')
       break;
     case '10003':
       message.error('密码错误')
       break;
     default:
       message.success('登录成功')
       // 存储信息到本地以及状态管理器
       const result = res.data.data
       localStorage.setItem('loginState', 'true')
       localStorage.setItem('adminname', result.adminname)
       localStorage.setItem('token', result.token)
       localStorage.setItem('role', result.role + '')
       localStorage.setItem('checkedkeys', JSON.stringify(result.checkedkeys))

       // rtk
       dispatch(changeLoginState(true))
       dispatch(changeAdminName(result.adminname))
       dispatch(changeToken(result.token))
       dispatch(changeRole(result.role))
       dispatch(changeCheckedkeys(result.checkedkeys))

       // 应该要跳转到系统首页 
       // navigate('/', { replace: true })
       // redirectUrl ? navigate(redirectUrl, { replace: true }) : navigate('/', { replace: true }) // 发现无效
       break;
   }
 })
}
return (
 <div id='components-form-demo-normal-login'>
   <Form
     name="normal_login"
     className="login-form"
     initialValues={{ remember: true }}
     onFinish={onFinish}
   >
     <h1 id='components-form-demo-normal-login-title'>喜茶后台管理系统</h1>
     <Form.Item
       name="adminname"
       rules={[{ required: true, message: '请输入管理员账户!' }]}
     >
       <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" allowClear/>
     </Form.Item>
     <Form.Item
       name="password"
       rules={[{ required: true, message: '请输入密码!' }]}
     >
       <Input
         prefix={<LockOutlined className="site-form-item-icon" />}
         type="password"
         placeholder="密码"
         allowClear
       />
     </Form.Item>

     <Form.Item>
       <Button type="primary" htmlType="submit" className="login-form-button">
         登 录
       </Button>
     </Form.Item>
   </Form>
 </div>
)
}